#include "apue.h"
#include <errno.h>
#include <sys/wait.h>

int system(const char *cmdstring);

int main(int argc, char *argv[]) {
    int status;
    if ((status = system("data")) < 0) {
        err_sys("system() error");
    }
    pr_exit(status);

    if ((status = system("nosuchcommand")) < 0) {
        err_sys("system() error");
    }
    pr_exit(status);

    if ((status = system("who; exit 44")) < 0) {
        err_sys("system() error");
    }
    pr_exit(status);

    return 0;
}

int system(const char *cmdstring) {
    pid_t pid;
    int status;

    if (cmdstring == NULL) {
        exit(1);
    }

    if ((pid = fork()) < 0) {
        status = -1;
    } else if (pid == 0) { // child
        execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
        _exit(127); // execl error
    } else { // parent
        while (waitpid(pid, &status, 0) < 0) {
            if (errno != EINTR) {
                status = -1;
                break;
            }
        }
    }
    return status;
}